const db = wx.cloud.database();

Page({
  data: {
    announcements: []
  },

  onLoad(options) {
    this.getAnnouncements();
  },

  onShow() {
    this.getAnnouncements(); // 每次页面显示时刷新数据
  },

  onPullDownRefresh() {
    this.getAnnouncements(() => {
      wx.stopPullDownRefresh();
    });
  },

  getAnnouncements(callback) {
    db.collection('message').orderBy('createTime', 'desc').get({
      success: res => {
        const announcements = res.data.map(item => {
          item.createTime = this.dateFormat(item.createTime, 'YYYY-MM-DD hh:mm:ss');
          return item;
        });
        this.setData({ announcements });
        if (callback) callback();
      },
      fail: err => {
        wx.showToast({ title: '获取公告失败，请稍后重试', icon: 'none' });
      }
    });
  },

  dateFormat(date, fmt) {
    let ret;
    const opt = {
      "Y+": date.getFullYear().toString(),
      "M+": (date.getMonth() + 1).toString(),
      "D+": date.getDate().toString(),
      "h+": date.getHours().toString(),
      "m+": date.getMinutes().toString(),
      "s+": date.getSeconds().toString()
    };
    for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
        fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")));
      }
    }
    return fmt;
  }
});
